package org.yong.springbootcmd.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.yong.springbootcmd.model.vo.WsProtocol;

import java.io.BufferedReader;
import java.io.InputStreamReader;

@Slf4j
@Service
public class WindowsWsProtocolHandlerImpl extends WsProtocolHandlerBaseImpl {

    @Override
    public int getMainCmd() {
        return 1;
    }

    @Override
    protected WsProtocol doHandle() {
        WsProtocol ret = super.doHandle();
        ret.setE(0);
        ret.setEs(null);

//        int b = this.param.getB();
//        if (1 == b) this.param.setD("dir");
        this.exec(ret);

        return ret;
    }

    private void exec(WsProtocol ret) {
        Runtime runtime = Runtime.getRuntime();
        Process p = null;
        StringBuilder buf = new StringBuilder();
        try {
            String cmd = String.format("cmd /C %s", param.getD());
            log.info(String.format("执行的CMD: %s", cmd));
            p = runtime.exec(cmd);
            try (
                    InputStreamReader isr = new InputStreamReader(p.getInputStream(), "GBK");
                    BufferedReader br = new BufferedReader(isr)
            ) {
                // 将命令执行结果保存到文件中
                String line;
                while ((line = br.readLine()) != null)
                    buf.append(line).append("\n");
            }

            ret.setD(buf);
            log.info(buf.toString());
        } catch (Exception e) {
            ret.setE(-1);
            ret.setEs(e.getMessage());
            log.warn(e.getMessage(), e);
        } finally {
            if (p != null)
                p.destroy();
        }
    }
}
